﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.Windows.Media.Animation;
using DiasEngineDate.UI;
using Microsoft.Win32;
using System.Windows.Resources;
using System.Net.Sockets;
using System.Net;
using DiasEngineDate.UI.InventoryInformation;

namespace DiasEngineDate
{
    /// <summary>
    /// Main.xaml 的交互逻辑
    /// </summary>
    public partial class Main : Window
    {
        //判断软件是否注册
        public bool IsReged = false;
        DiasRegister softReg = new DiasRegister();

        /*
        * 进度时间设置1
        */
        private TimeSpan duration;
        private DispatcherTimer timer = new DispatcherTimer();
        private OpenFileDialog videoDialog = new OpenFileDialog();
        private bool isPlaying = false;
        /*
       * 进度时间设置1
       */

        //鼠标移除10秒后隐藏视频控制按钮
        DispatcherTimer timervideocontrol = new DispatcherTimer();

        #region 服务器变量


        string[] splitString;//获取客户端传过来的信息处理

        //引用配置文件库
        [DllImport("kernel32")] ///获取系统时间
        public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);

        ///定义系统时间结构信息
        [StructLayout(LayoutKind.Sequential)]
        public struct SYSTEMTIME_INFO
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }

        //网络连接状态。判断是否连接到服务器
        bool netstat = false;

        bool isWatch = true;
        Dictionary<string, ConnectionClient> dictConn = new Dictionary<string, ConnectionClient>();

        Socket sokWatch = null;//负责监听 客户端段 连接请求的  套接字(女生宿舍的大妈)
        Thread threadWatch = null;//负责 调用套接字， 执行 监听请求的线程
        //1.被线程调用 监听连接端口
        //被线程调用 监听连接端口
        void StartWatch()
        {
            string recode;
            while (isWatch)
            {
                //threadWatch.SetApartmentState(ApartmentState.STA);
                //监听 客户端 连接请求，但是，Accept会阻断当前线程
                Socket sokMsg = sokWatch.Accept();//监听到请求，立即创建负责与该客户端套接字通信的套接字
                ConnectionClient connection = new ConnectionClient(sokMsg, ShowMsg, RemoveClientConnection);
                //将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合

                //识别用户登录的用户名和操作

                dictConn.Add(sokMsg.RemoteEndPoint.ToString(), connection);
                //将 通信套接字 加入 集合，并以通信套接字的远程IpPort作为键
                //dictSocket.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg);
                //将 通信套接字的 客户端IP端口保存在下拉框里
                addcbolist(sokMsg.RemoteEndPoint.ToString());
                //提示有新用户登录
                //发送数据返回到客户端。提示发送成功
                //dictConn[sokMsg.RemoteEndPoint.ToString()].Send("服务器连接成功......当前网络环境[局域网].安全系数：98%");


                recode = sokMsg.RemoteEndPoint.ToString();


                dictConn[sokMsg.RemoteEndPoint.ToString()].SendTrue();

                foreach (ConnectionClient conn in dictConn.Values)
                {
                    //发送群信息
                    //conn.Send("全部用户听着.你们被包围了.");
                }
            }
        }

        //添加客户端列表到combobox
        private void addcbolist(string _remoteendpoint)
        {
            if (Clientlist.CheckAccess())
            {
                Clientlist.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                {
                    Clientlist.Items.Add(_remoteendpoint);
                    MSGToBox(DateTime.Now.ToString(), _remoteendpoint + "连接服务器", false);
                }));
                return;
            }////////////////////////////////////
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                Clientlist.Items.Add(_remoteendpoint);
                MSGToBox(DateTime.Now.ToString(), _remoteendpoint + "连接服务器", false);
            });
        }

        //向文本框显示消息 -void ShowMsg(string msgStr)
        // 向文本框显示消息
        // <param name="msgStr">消息</param>
        public void ShowMsg(string msgStr)
        {
            if (TxtShow.CheckAccess())
            {
                Clientlist.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                {
                    TxtShow.AppendText(msgStr + "\n");
                    MSGToBox(DateTime.Now.ToString(), msgStr, false);
                }));
                return;
            }
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                TxtShow.AppendText(msgStr + "\n");
                MSGToBox(DateTime.Now.ToString(), msgStr, false);
            });
        }


        //删除客户端列表
        public void removecbolist(string _key)
        {
            if (Clientlist.CheckAccess())
            {
                Clientlist.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                {
                    Clientlist.Items.Remove(_key);
                    Clientlist.UpdateLayout();
                }));
                return;
            }
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                Clientlist.Items.Remove(_key);
            });
        }

        //移除与指定客户端的连接
        public void RemoveClientConnection(string key)
        {

            if (dictConn.ContainsKey(key))
            {
                dictConn.Remove(key);
                removecbolist(key);
            }
        }
        #endregion

        //引用配置文件库
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


        //客户端信息窗体

        FunctionINC inc = new FunctionINC();
        DiasNetClientStdio DNCS;

        public Main()
        {
            InitializeComponent();
            Monitor.PartEvent += OnStep;//将该类中的函数注册到Monitor静态类的PartEvent
        }

        //实现类中访问主窗体控件
        public void OnStep(Object sender, MessageArgs message)
        {

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                ClientInfo.Text += message.TxtMessage;//设置对应xaml中控件的属性
            }));
        }
        


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (Login.SuserName=="admin")
            {
                //向客户端提示服务端关闭，可以为所欲为
                string time;
                foreach (ConnectionClient conn in dictConn.Values)
                {
                    conn.Send("服务器已经关闭.您已断开和服务器连接...");
                }
                Thread closeth = new Thread(ISCLOSING);
                closeth.Start();
            }
            else
            {
                DNCS.DiasClientExit();//发送退出软件命令
                Thread closeth = new Thread(ISCLOSING);
                closeth.Start();
            }
            
        }


        //变量，记录窗口目前最大化或默认状态
        bool ismax = false;
        bool menushow = true;
        bool configshow = false;
        bool movieshow = false;

        MainContents msc;
        //页面按钮方法
        private void TheButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender as Button;
            if (btn.Name == "close_btn")//关闭按钮
            {
                this.Close();
            }
            else if (btn.Name == "max_btn")//最大化
            {
                if (ismax)
                {
                    this.WindowState = WindowState.Normal;//默认窗口
                    ismax = false;
                }
                else
                {
                    this.WindowState = WindowState.Maximized;//最大化窗口
                    ismax = true;
                }
            }
            else if (btn.Name == "mix_btn")//最小化
            {
                this.WindowState = WindowState.Minimized;
            }
            else if (btn.Name == "skin_btn")//更换背景
            {
                //使用线程启动背元素
                Thread settbg = new Thread(new ThreadStart(SettingBackground));
                //settbg.SetApartmentState(ApartmentState.STA);
                settbg.Start();
            }
            else if (btn.Name == "CenterBtn")//隐藏或打开菜单栏
            {
                ShowHiddenMenu();
            }
            else if (btn.Name == "SystemInfos")//打开系统信息
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                SystemInfos sis = new SystemInfos(Home, MainContents, RightContent);
                msc = new MainContents(sis);
                MainContents.Child = msc;
            }
            else if (btn.Name == "ConfigControl")//打开控制面板
            {
                ConfigBox.Visibility = System.Windows.Visibility.Visible;
                MainBox.Visibility = System.Windows.Visibility.Hidden;
                configshow = true;
            }
            else if (btn.Name == "closeconfig")//关闭控制面板
            {
                ConfigBox.Visibility = System.Windows.Visibility.Hidden;
                MainBox.Visibility = System.Windows.Visibility.Visible;
                configshow = false;
            }
            else if (btn.Name == "MovieCtrl")//视频控制面板
            {
                MovieBox.Visibility = System.Windows.Visibility.Visible;
                MainBox.Visibility = System.Windows.Visibility.Hidden;
                //MovieControl.Visibility = System.Windows.Visibility.Visible;
                movieshow = true;
                this.timer.Start();//启动让进度条显示播放进度
                video.Play();
            }
            else if (btn.Name == "PLast")//快退
            {
                video.Position = this.video.Position - TimeSpan.FromSeconds(20);
            }
            else if (btn.Name == "PNext")//快进
            {
                video.Position = video.Position + TimeSpan.FromSeconds(20);
            }
            else if (btn.Name == "PPlay")//播放
            {
                video.Play();
            }
            else if (btn.Name == "PStop")//停止
            {
                video.Stop();
            }
            else if (btn.Name == "PPause")//暂停
            {
                video.Pause();
            }
            else if (btn.Name == "CloseMovie")//关闭视频控件框
            {
                MovieBox.Visibility = System.Windows.Visibility.Hidden;
                MovieControl.Visibility = System.Windows.Visibility.Hidden;
                MainBox.Visibility = System.Windows.Visibility.Visible;
                movieshow = false;
                this.timer.Stop();//停止时间记录。减少资源损耗
                video.Pause();
            }
            else if (btn.Name == "Rolebtn")//打开角色面板
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Role r = new Role(Home, MainContents);
                msc = new MainContents(r);
                MainContents.Child = msc;
            }
            else if (btn.Name == "Rightsbtn")//打开权限面板
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Rights r = new Rights(Home, MainContents, RightContent);
                msc = new MainContents(r);
                MainContents.Child = msc;
            }
            else if (btn.Name == "Toolsbtn")//打开工具版面
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Tools t = new Tools(Home, MainContents, RightContent);
                msc = new MainContents(t);
                MainContents.Child = msc;
            }
            else if (btn.Name == "CarModle_Btn")
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                CarModels cm = new CarModels(Home, MainContents, RightContent);
                msc = new MainContents(cm);
                MainContents.Child = msc;
            }
            else if (btn.Name == "ChipTypeBtn")
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Chip_Type ct = new Chip_Type(Home, MainContents, RightContent);
                msc = new MainContents(ct);
                MainContents.Child = msc;
            }
            else if (btn.Name == "KeyTypeBtn")
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Profit pf = new Profit(Home, MainContents, RightContent);
                msc = new MainContents(pf);
                MainContents.Child = msc;
            }
            else if (btn.Name == "QueryBtn")
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Inventory_Query iq = new Inventory_Query(Home, MainContents, RightContent);
                msc = new MainContents(iq);
                MainContents.Child = msc;

            }
            else if (btn.Name == "OutBtn")
            {
                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                In_Library ili = new In_Library(Home, MainContents, RightContent);
                msc = new MainContents(ili);
                MainContents.Child = msc;

            }
            else if (btn.Name == "InBtn")
            {
                

                MainContents.Visibility = System.Windows.Visibility.Visible;
                Home.Visibility = System.Windows.Visibility.Hidden;

                Out_Library ol = new Out_Library(Home, MainContents, RightContent);
                msc = new MainContents(ol);
                MainContents.Child = msc;
            }
            else if (btn.Name == "SendMSG")
            {
                
                //验证数据
                if (TxtInput.Text == "" || TxtInput.Text == "请再次输入系统信息.")
                {
                    TxtShow.AppendText("--您没有输入要发送的信息发送失败.\n");
                    return;
                }
                string time;
                foreach (ConnectionClient conn in dictConn.Values)
                {
                    conn.Send(TxtInput.Text.Trim());
                }
                SYSTEMTIME_INFO StInfo; StInfo = new SYSTEMTIME_INFO();
                GetSystemTime(ref StInfo);
                time = StInfo.wYear.ToString() + "/" + StInfo.wMonth.ToString() + "/" + StInfo.wDay.ToString() + "  ";
                time += (StInfo.wHour + 8).ToString() + ":" + StInfo.wMinute.ToString();
                TxtShow.AppendText("--"+time + "\n");
                TxtShow.AppendText("--群发消息：" + TxtInput.Text.Trim() + "\n");
                MSGToBox(DateTime.Now.ToString(), TxtInput.Text.ToString(), true);
                TxtInput.Text = "";
            }
            else if (btn.Name == "GetREG")
            {
                string time;
                foreach (ConnectionClient conn in dictConn.Values)
                {
                    try
                    {
                        conn.RegDate();
                        MSGToBox(DateTime.Now.ToString(), "--获取客户端注册码.", true);
                    }
                    catch (Exception)
                    {

                    }
                }
                SYSTEMTIME_INFO StInfo; StInfo = new SYSTEMTIME_INFO();
                GetSystemTime(ref StInfo);
                time = StInfo.wYear.ToString() + "/" + StInfo.wMonth.ToString() + "/" + StInfo.wDay.ToString() + "  ";
                time += (StInfo.wHour + 8).ToString() + ":" + StInfo.wMinute.ToString();
                TxtShow.AppendText("--"+time + "\n");
                MSGToBox(DateTime.Now.ToString(), TxtInput.Text.ToString(), true);

            }
            else if (btn.Name=="GetScreen")
            {
                string time;
                foreach (ConnectionClient conn in dictConn.Values)
                {
                    try
                    {
                        conn.jieping();                        
                    }
                    catch (Exception)
                    {

                    }
                }
                SYSTEMTIME_INFO StInfo; StInfo = new SYSTEMTIME_INFO();
                GetSystemTime(ref StInfo);
                time = StInfo.wYear.ToString() + "/" + StInfo.wMonth.ToString() + "/" + StInfo.wDay.ToString() + "  ";
                time += (StInfo.wHour + 8).ToString() + ":" + StInfo.wMinute.ToString();
                TxtShow.AppendText("--" + time + "\n");
                TxtShow.AppendText("--获取所有客户端屏幕\n");
            }
            else if (btn.Name=="Shaking")
            {
                foreach (ConnectionClient conn in dictConn.Values)
                {
                    conn.SendShake();
                    MSGToBox(DateTime.Now.ToString(), "--更新.", true);
                }
            }
            else if (btn.Name=="BTNREG")
            {
                SoftReg sr = new SoftReg();
                sr.ShowDialog();
            }
            else if(btn.Name=="Creaking")
            {
                //开始改变字体颜色
                //显示文字颜色改变
                Thread colors = new Thread(StarColors);
                colors.Start();   
            }
        }


        //选择背景
        private void SettingBackground()
        {
            this.video.Dispatcher.Invoke(new Action(() =>
            {
                inc.SettingVideo(this.video, Login.SEname);
            }));

        }

        //当正常打开背景图片
        private void video_MediaOpened(object sender, RoutedEventArgs e)
        {

            if (video.Source.ToString() != "")
            {
                if (inc.isImg(video.Source.ToString()))
                {

                }
                else
                {
                    try
                    {
                        //视频总时长
                        double seconds = video.NaturalDuration.TimeSpan.TotalSeconds;
                        //共分成10等分，每1等分多少秒
                        Postionloading.Maximum = seconds / 10;
                        //10分之一
                        double baseSecond = seconds / Postionloading.Maximum;
                        this.timer.Interval = new TimeSpan(0, 0, 1);
                        this.timer.Tick += new EventHandler(timer_Tick);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        //成功打开的时间方法
        void timer_Tick(object sender, EventArgs e)
        {
            this.Postionloading.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(timelineSlider_ValueChanged);
            this.Postionloading.Value = this.video.Position.TotalSeconds / 10.0;
            this.Postionloading.ValueChanged += new RoutedPropertyChangedEventHandler<double>(timelineSlider_ValueChanged);
            try
            {
                playstart.Content = string.Format("{0}{1:00}:{2:00}:{3:00}", "", video.Position.Hours, video.Position.Minutes, video.Position.Seconds);
                playend.Content = string.Format("{0}{1:00}:{2:00}:{3:00}", "", video.NaturalDuration.TimeSpan.Hours, video.NaturalDuration.TimeSpan.Minutes, video.NaturalDuration.TimeSpan.Seconds);
            }
            catch { }
        }

        //播放进度，跳转到播放的哪个地方
        private void timelineSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TimeSpan span = new TimeSpan(0, 0, (int)(Postionloading.Value) * 10);
            video.Position = span;
        }


        string[] str = { 
            //"All Of The World Be Careful-Black-Hat[Lucifer__HaCkeR]!",
            //"Lucifer__HaCkeR W4s Here!",
            //"-==[ We Love Hacker ]==-",
            //"# I Don't Lov3 = Fascist (ISREAL [&] Amrican ...) ",
            //"Im Here...!!!! :)))) ",
            //"Email :Root@diasoo.com !! o_0 !! ",
            //"!! o_0 !!",
            //"My Home Is Near ..... My Home Is : Everywhere [ International Dangerous Hackers ] ",
            //"Contact: Root@Diasoo.com",
            //"My Site:http://Diasoo.com",
            //"Plz Click Here ==>> International Hackers",
            //"CopyRight By Lucifer__HaCkeR |-> I' Defacer [Lucifer__HaCkeR]",
            //"....Broken My Heart So be Careful Your Computer Is Hacked By me All Of The World Be Careful...."
            "正在破解权限...",
            "正在尝试登录administrator账户...",
            "权限破解中.即将获取超级管理员权限...",
            "成功获得超级管理员权限...",
            "正在打开GPS卫星定位系统...",
            "成功获得目标坐标,现已经锁定目标地址...",
            "成功进入目标1000米内摄像头权限...",
            "相关视频信息已经发送到主机...",
            "紧急提示：服务器存储容量即将满载,是否启动分布式自动存储...",
            "成功分析系统漏洞：SQL注入，端口号：3389，23，21端口开放，服务器已经成功植入木马端口：7626...",
            "成功劫持整个目标内网DNS，现在等待肉鸡反馈您需要的信息...",
            "目标服务器已经破解成功，现即将开始格式化整个服务器数据...",
            "欢迎您：系统管理员administrator，此次登录密码为：anonymous...",
            "系统破解成功...",
            "Hacked By Ownner Lucifer.本次入侵一共耗时10分52秒，共破解服务器1380个，获取数据120TB，图片和视频已经发到分享服务器...",
            "本次入侵代号：“坠落天使的醒悟。”纪念西楚霸王没落千年。",
            "正在破解请稍等..."
        };


        Random r = new Random();
        private void StarColors()
        {
            Thread.Sleep(TimeSpan.FromSeconds(0.2));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText(str[r.Next(str.Length)]+"\n");
                this.TxtShow.ScrollToEnd();
                byte b1 = (byte)(r.Next(0, 255));
                byte b2 = (byte)(r.Next(0, 255));
                byte b3 = (byte)(r.Next(0, 255));
                Color color = Color.FromRgb(b1,b2,b3);
                this.TxtShow.Foreground = new SolidColorBrush(color);


                //设置窗体所有控件字体颜色
                foreach (UIElement element in mainbig.Children)
                {
                    if (element is Label)
                    {
                        this.TxtShow.AppendText((element as Label).Content.ToString() + "\n");
                    }
                } 

                Thread colors = new Thread(StarColors);
                colors.Start();
            });
        }
        //不断的改变主页文本的字体颜色

        //窗口加载
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.TxtShow.AppendText("                                                                          ...;vStffM1;;;;...\n");
            this.TxtShow.AppendText("                                                              .,,7Qlltt8jj8jjjjjjjjjjj88jj88jj86tr;;.  \n");
            this.TxtShow.AppendText("                                                            1Sgjj88jj88jj88jj88jjj8jjjj88jjjjj@V:::.\n");
            this.TxtShow.AppendText("                                                            rABtt:::.                         .,,,;;;0jj@y...\n");
            this.TxtShow.AppendText("                                                            gE7......11;;:::,...          ..,:::;;;;;;;,,,,..y88jjjj1;\n");
            this.TxtShow.AppendText("                                                          ..G6ll...H5#gjjjjjjrr;...  :M8jjj666#,,,:;Wjgirr\n");
            this.TxtShow.AppendText("                                                         u0jj7;:......,::::::;;1kAi  .::J4V1;;:::...,:::,,,:mjEqsu;\n");
            this.TxtShow.AppendText("                                                       .:wjjjBJ;...,:::;;;;;;;;;;:,,,:::,...:::;v;,,,;;;;:::11;;:::;mjjj8jjjj;;;,\n");
            this.TxtShow.AppendText("                                                          ,,,gsv...  ..........   ...     :::.    ........,,,,,,;mjBt\n");
            this.TxtShow.AppendText("                                                              .:::::uH7:::.......;;;;;;;:::;;;;,,,,,,,,,,;vvr;;;:,,,:::.\n");
            this.TxtShow.AppendText("                                                              ItT1rrgqiw2BjM@EV1W8PVT1: \n");
            this.TxtShow.AppendText("                                                                .;;;;;;;;;;;;;;;;;;;;;;;;:::::::;1111IIv1;;;,,, \n");
            this.TxtShow.AppendText("                                                                   ...:;;;:::,...    A8H  ...,,,:;;;1; \n");
            this.TxtShow.AppendText("                                                                     ,::1w1...  zjjm  :::LwJ::: \n");
            this.TxtShow.AppendText("                                                                 ...,,,,,,,;;Lt0QZ8AwiEM;;;......\n");
            this.TxtShow.AppendText("                                                       .;;1r;;;;;;;1r:::,...,,,:::1yqiiiWM7;;;...     1rmJ11rV71,,,........... \n");
            this.TxtShow.AppendText("                                   ...:::...:;;;;;;;;;;,,,:;;Tkk1;:::::::;1111,,,.......,:::;;;;;;;::::,,,     ...w##lr1:::...:1LrJv1;;;;:::1;;;;;;;;... \n");
            this.TxtShow.AppendText("                              ,,,...,:::;;;;::::::;1:...:::Lu1;;;;;;::::;;;;1vCiqsJ11;;11v1r:::;1zt8jjj@lWIr.......,,,...,:::17n1111V1;:::,...\n");
            this.TxtShow.AppendText("                           :Jv1;;;;;;1Pjjjjjjjjjjjj88jjfttQqll4i5ll0fAM@g@fE45E88jj45tMtt5@88jjj8jjjj#TUwJv7uvrr;;;:,,,\n");
            this.TxtShow.AppendText("                         ;;vUwr1;;  4j88jjjjjjjjj8BlQ#f#f6EgEQlll#EQ54f#tq54f#ftZqqiiQg8jjjjjjjjBv:  ...,::uyUJIT;;;::::\n");
            this.TxtShow.AppendText("                       ,,,4Cr:::.       ;Ujj8g8jjjjjjjjjjjjj#r;;1r;;;17V;;;;;;ryyr;;;:::;1wIJCI;;;1z8jjjjjjjjjjgg8D::.           .:::msJ;;;1:.. \n");
            this.TxtShow.AppendText("                    ....m;;;              1zjj88jj88jj88gE@E88gE4@88@@@@E@0jjjjjjjjjj88jj88jj...,:::...            ;;1I1;;:::. \n");
            this.TxtShow.AppendText("                    :rr...            ...,:mj#l2VA#8jjjgE@g6llll#Ejjjgg0btt4qiE8jjH@ffiiig8jjt4Dgjjjr::.                J1;;;:::... \n");
            this.TxtShow.AppendText("                  ;;;;;;;         ....;;;;;;;,,M8jjjjjjjjjjjjjjjjjjjjjju5jjEbz8jjjj8jjjj88jjj8jjjj8jjjj86q4A7Ajj86ii5#88r::::::.......;;;:,,,...   ;;1r1;;;;;... \n");
            this.TxtShow.AppendText("                  ...                     ....                 ..                                 .......            ......          ,,,:::,...\n");
            inc.LoadingMain(mainbig);
            //登录成功播放声音
            inc.PlayerAudio(@"Start.wav ");

            //登录成功，读取用户设置的背景图片
            inc.SettingLoginUserBackground(Login.SEname, video);
            isPlaying = true;

            //设置用户头像
            //inc.SettingLoginUserPhoto(Login.SEname, ellipseWithImageBrush);

            //设置鼠标光标
            Cursor custoCursor = new Cursor(System.AppDomain.CurrentDomain.BaseDirectory + @"Cursor\Arrow.cur");
            this.Cursor = custoCursor;
            //StreamResourceInfo sri = Application.GetResourceStream(new Uri(@"Cursor\Arrow.cur", UriKind.Relative));
            //Cursor customCursor = new Cursor(sri.Stream);
            //this.Cursor = customCursor;


            //读取用户列表
            //inc.BingdingSysUserDataGrid(SystemUserList);

            //添加启动信息

            //绑定头像、用户名、系统级别
            //设置用户头像
            ImageBrush imgBrush = new ImageBrush();
            imgBrush.ImageSource = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"SysUserImg\" + Login.SuserImg, UriKind.Absolute));
            ellipseWithImageBrush.Fill = imgBrush;
            Eusername.Content=Login.SuserName;
            AutherName.Content = Login.Suser;



            //判断登录用户启动服务端或客户端
            if (Login.SuserName=="admin")
            {
                ServerWin.Visibility = System.Windows.Visibility.Visible;
                ClientWin.Visibility = System.Windows.Visibility.Hidden;
                //如果是管理员。启动服务器
                Thread startServices = new Thread(StartingServer);
                startServices.Start();

                Thread th1 = new Thread(PrintONE);
                th1.Start();
                Thread th2 = new Thread(PrintTWO);
                th2.Start();
                Thread th3 = new Thread(PrintTHREE);
                th3.Start();
                Thread th4 = new Thread(PrintFOUR);
                th4.Start();
                Thread th5 = new Thread(PrintFIVE);
                th5.Start();
            }
            else
            {
                Thread th1 = new Thread(PrintONE);
                th1.Start();
                Thread th2 = new Thread(PrintTWO);
                th2.Start();
                Thread th3 = new Thread(PrintTHREE);
                th3.Start();
                Thread th4 = new Thread(PrintFOUR);
                th4.Start();
                Thread th5 = new Thread(PrintFIVE);
                th5.Start();


                DNCS = new DiasNetClientStdio();//客户端类初始化,判断是客户端身份启动才初始化它

                ServerWin.Visibility = System.Windows.Visibility.Hidden;
                ClientWin.Visibility = System.Windows.Visibility.Visible;
                //如果是客户端启动窗口连接服务器,使用进程
                Thread startconnectserver = new Thread(StartConnecting);
                startconnectserver.Start();

                //客户端登录需要注册软件
                //软件注册检测开始
                //判断软件是否注册
                if (IsReged)
                {

                }
                else
                {
                    Thread regthread = new Thread(ISREG);
                    regthread.Start();
                }

            }
        }

        //显示或隐藏菜单栏
        private void ShowHiddenMenu()
        {
            //隐藏
            DoubleAnimation dfrom = new DoubleAnimation();
            dfrom.From = 160;
            dfrom.To = 0;
            dfrom.Duration = TimeSpan.FromSeconds(0.2);
            DoubleAnimation dfromo = new DoubleAnimation();
            dfromo.From = 1;
            dfromo.To = 0;
            dfromo.Duration = TimeSpan.FromSeconds(0.1);

            //显示
            DoubleAnimation dto = new DoubleAnimation();
            dto.From = 0;
            dto.To = 160;
            dto.Duration = TimeSpan.FromSeconds(0.2);
            DoubleAnimation dtoo = new DoubleAnimation();
            dtoo.From = 0;
            dtoo.To = 1;
            dtoo.Duration = TimeSpan.FromSeconds(0.1);


            //logo显示
            DoubleAnimation dalogo = new DoubleAnimation();
            dalogo.From = 0;
            dalogo.To = 160;
            dalogo.Duration = TimeSpan.FromSeconds(0.2);
            DoubleAnimation dalogoo = new DoubleAnimation();
            dalogoo.From = 0;
            dalogoo.To = 1;
            dalogoo.Duration = TimeSpan.FromSeconds(0.1);

            //logo隐藏
            DoubleAnimation dalogohid = new DoubleAnimation();
            dalogohid.From = 160;
            dalogohid.To = 0;
            dalogohid.Duration = TimeSpan.FromSeconds(0.2);
            DoubleAnimation dalogohido = new DoubleAnimation();
            dalogohido.From = 1;
            dalogohido.To = 0;
            dalogohido.Duration = TimeSpan.FromSeconds(0.1);

            if (menushow)
            {
                LeftMenu.BeginAnimation(FrameworkElement.WidthProperty, dfrom);
                LeftMenu.BeginAnimation(FrameworkElement.OpacityProperty, dfromo);
                Menubox.Width = (System.Windows.GridLength.Auto);

                //logo
                logobg.BeginAnimation(FrameworkElement.WidthProperty, dalogohid);
                logobg.BeginAnimation(FrameworkElement.OpacityProperty, dalogohido);
                titlebo.BeginAnimation(FrameworkElement.OpacityProperty, dalogohido);

                menushow = false;
            }
            else
            {
                LeftMenu.BeginAnimation(FrameworkElement.WidthProperty, dto);
                LeftMenu.BeginAnimation(FrameworkElement.OpacityProperty, dtoo);
                Menubox.Width = System.Windows.GridLength.Auto;

                //logo
                logobg.BeginAnimation(FrameworkElement.WidthProperty, dalogo);
                logobg.BeginAnimation(FrameworkElement.OpacityProperty, dalogoo);
                titlebo.BeginAnimation(FrameworkElement.OpacityProperty, dalogoo);


                menushow = true;
            }
        }

        //设置背景图片
        private void SettingBG()
        {
            //读取背景图片
            //string bgname = Encryption_Decryption.Decrypt(IniReadValue("VideoURL", "videourl", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));

            //应用背景
            //this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            //{
            //inc.SettingVideosbg(video, Login.Suser);
            //});

        }

        //读取INI文件方法
        static public string IniReadValue(string Section, string Key, string filepath)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, filepath);
            return temp.ToString();
        }

        //当鼠标移入到时间轴
        private void SliderTimer_MouseMove(object sender, MouseEventArgs e)
        {
            ShowTheOpacity(MovieControl);
            timervideocontrol.Interval = new TimeSpan(0, 0, 10);
            timervideocontrol.Tick += new EventHandler(timervideocontrol_Tick);

        }
        //当鼠标移出时间轴
        private void SliderTimer_MouseLeave(object sender, MouseEventArgs e)
        {
            timervideocontrol.Start();
        }


        //状态变量
        //播放器时间轴和按钮隐藏显示动画
        public void ShowTheOpacity(Grid _btn)
        {
            MovieControl.Visibility = System.Windows.Visibility.Visible;
            DoubleAnimation dashow = new DoubleAnimation();
            dashow.From = 0;
            dashow.To = 1;
            dashow.Duration = TimeSpan.FromSeconds(0.5);

            _btn.BeginAnimation(FrameworkElement.OpacityProperty, dashow);
        }
        public void HiddenTheOpacity(Grid _btn)
        {
            MovieControl.Visibility = System.Windows.Visibility.Hidden;
            DoubleAnimation dahide = new DoubleAnimation();
            dahide.From = 1;
            dahide.To = 0;
            dahide.Duration = TimeSpan.FromSeconds(0.5);
            _btn.BeginAnimation(FrameworkElement.OpacityProperty, dahide);
        }
        public void timervideocontrol_Tick(object sender, EventArgs e)
        {
            HiddenTheOpacity(MovieControl);
            timervideocontrol.Stop();
        }

        //显示内容区域动画
        public void ShowContentWin(Border _border)
        {
            DoubleAnimation dashowopacity = new DoubleAnimation();
            dashowopacity.From = 0;
            dashowopacity.To = 1;
            dashowopacity.Duration = TimeSpan.FromSeconds(1);
            _border.BeginAnimation(FrameworkElement.OpacityProperty, dashowopacity);
        }
        //隐藏内容区域动画
        public void HiddenContentWin(Border _border)
        {
            DoubleAnimation dahiddenapacity = new DoubleAnimation();
            dahiddenapacity.From = 1;
            dahiddenapacity.To = 0;
            dahiddenapacity.Duration = TimeSpan.FromSeconds(0.5);
            _border.BeginAnimation(FrameworkElement.OpacityProperty, dahiddenapacity);
        }
        //当播放视频结束
        private void video_MediaEnded(object sender, RoutedEventArgs e)
        {
            video.Stop();
            video.Play();
        }

        //启动服务器
        private void StartingServer()
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                //启动服务器
                //实例化 套接字 （ip4寻址协议，流式传输，TCP协议）
                sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //创建 ip对象
                //IPAddress address = IPAddress.Parse(Convert.ToString(Encryption_Decryption.Decrypt(IniReadValue("Server", "server", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"))));//读取配置文件，ip地址并且解密
                IPAddress address = IPAddress.Parse("127.0.0.1");
                IPEndPoint endpoint = new IPEndPoint(address, int.Parse("8885"));//设置端口号为8885
                //将 监听套接字  绑定到 对应的IP和端口
                try
                {
                    sokWatch.Bind(endpoint);
                    //设置 监听队列 长度为10(同时能够处理 10个连接请求)
                    sokWatch.Listen(50);
                    threadWatch = new Thread(StartWatch);
                    threadWatch.IsBackground = true;
                    threadWatch.Start();
                    this.TxtShow.AppendText("--服务器已经启动成功,正在监听端口：8885,等待客户端连接......\n");

                    //在前台添加xaml代码
                    MSGToBox(DateTime.Now.ToString(), "--服务器已经启动成功,正在监听端口：8885,等待客户端连接......", false);

                }
                catch (Exception ex)
                {
                    this.TxtShow.AppendText("--服务器启动失败.\n失败原因：" + ex);
                    MSGToBox(DateTime.Now.ToString(), "--服务器启动失败.失败原因：" + ex, false);
                }
            });
        }

        //在在消息页面显示消息
        public void MSGToBox(string _time, string _msg, bool _cs)
        {
            //在前台添加xaml代码
            StackPanel sp = new StackPanel();
            Label ll = new Label();
            ll.HorizontalAlignment = HorizontalAlignment.Center;
            Color c = Color.FromArgb(0, 0, 0, 0);
            ll.Foreground = new SolidColorBrush(c);

            ll.Content = _time.ToString();
            iDecorator i = new iDecorator();

            i.HorizontalAlignment = HorizontalAlignment.Right;
            i.Direction = _cs;
            TextBlock tb = new TextBlock();
            tb.MaxWidth = 200;
            Color c1 = Color.FromArgb(255, 0, 0, 0);
            tb.Foreground = new SolidColorBrush(c1);
            tb.TextWrapping = TextWrapping.Wrap;
            tb.Text = _msg;
            sp.Children.Add(ll);
            sp.Children.Add(i);
            i.Child = tb;
            //UserInfoBox.Children.Add(sp);
            Rectangle r = new Rectangle();
            r.Height = 20;
            //UserInfoBox.Children.Add(r);
        }

        //连接服务器
        private void StartConnecting()
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                DNCS.StartConnectingServer(netstat);
            });

        }

        //检测软件是否注册
        private void ISREG()
        {
            IsReged = true;
            Thread.Sleep(TimeSpan.FromSeconds(10));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                RegistryKey retkey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true).CreateSubKey("Dias").CreateSubKey("Dias.INI");
                foreach (string strRNum in retkey.GetSubKeyNames())
                {
                    if (strRNum == softReg.GetRNum())
                    {
                        this.TxtShow.AppendText("--缔亚智能核心引擎正版授权(旗舰版.注册号:DIAS.All Right For Client Once[DEBUG-0101-A673-E495-K908]).\n");
                        return;
                    }
                }
                try
                {
                    this.TxtShow.AppendText("--缔亚智能引擎尚未注册.剩余使用次数[" + (30 - Convert.ToInt32((Int32)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", 0))) + "]次.\n");
                    DNCS.SendInformation("--" + DateTime.Now.ToString() + "\n--用户：" + Login.Suser + "[" + Login.SuserName + "]剩余使用次数[" + (30 - Convert.ToInt32((Int32)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", 0))) + "次.\n");
                }
                catch (Exception)
                {
                    
                }
                Int32 tLong;
                try
                {
                    tLong = (Int32)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", 0);
                }
                catch
                {
                    ClientInfo.Text = "--欢迎你："+Login.Suser+"["+Login.SuserName+"].这是您第一次试用本软件,软件试用次数30次,次数超过将不能使用,请您支持正版.及时购买正版授权.\n--缔亚智软数据驱动引擎版权所有.\n";
                    DNCS.SendInformation("--" + DateTime.Now.ToString() + "\n--用户：" + Login.Suser + "[" + Login.SuserName + "]第一次试用软件.\n");
                    Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", 0, RegistryValueKind.DWord);
                }
                tLong = (Int32)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", 0);
                if (tLong < 30)
                {
                    int tTimes = tLong + 1;
                    Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Dias", "UseTimes", tTimes);
                }
                else
                {
                    SystemInformations ainfo = new SystemInformations("软件到期提醒", "您的试用次数已经达到30次,请您购买正版授权,请向软件运营商购买正版.");
                    ainfo.ShowDialog();
                    //DialogResult result = MessageBox.Show("试用次数已到！您是否需要注册？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (ainfo.TheResult == "OK")
                    {
                        //SoftReg.stat = false;
                        SoftReg frmRegister = new SoftReg();
                        frmRegister.ShowDialog();
                    }
                    else
                    {
                        SystemInformations sir = new SystemInformations("试用结束", "您的试用次数上限,软件即将退出,若要继续使用请您提供正确的注册码.");
                        sir.ShowDialog();
                        if (Login.SuserName == "admin")
                        {
                        }
                        else
                        {
                            DNCS.SendInformation("--"+DateTime.Now.ToString()+"\n--用户："+Login.Suser+"["+Login.SuserName+"]因未注册,试用次数上限,已经被系统强制关闭软件.\n");
                            DNCS.DiasClientExit();//发送退出软件命令
                        }

                        Thread thc = new Thread(ISCLOSING);
                        thc.Start();
                    }
                }
            });
        }

        //延迟1秒关闭窗口
        private void ISCLOSING()
        {
            Thread.Sleep(TimeSpan.FromSeconds(2));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                Application.Current.Shutdown(-1);
                Environment.Exit(0);
            });
        }

        private void TxtInput_MouseUp(object sender, MouseButtonEventArgs e)
        {
            TxtInput.Text = "";
        }

        //延迟输出登录信息
        private void PrintONE()
        {
            Thread.Sleep(TimeSpan.FromSeconds(2));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText("--欢迎您：" + Login.Suser + "[" + Login.SuserName + "].\n");
            });
        }
        private void PrintTWO()
        {
            Thread.Sleep(TimeSpan.FromSeconds(4));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText("--数据核心模块加载完成.\n");

            });
        }
        private void PrintTHREE()
        {
            Thread.Sleep(TimeSpan.FromSeconds(6));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText("--UI加载完成,程式初始化完成.\n");

            });
        }
        private void PrintFOUR()
        {
            Thread.Sleep(TimeSpan.FromSeconds(8));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText("--权限模块设定成功.\n");

            });
        }
        private void PrintFIVE()
        {
            Thread.Sleep(TimeSpan.FromSeconds(10));
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                this.TxtShow.AppendText("--缔亚智软数据驱动版权所有.\n");
            });
        }
    }
}
